<template>
	<view class="chat-bottom" :chatMsg="chatMsg" :change:chatMsg="msg.inputMsg" :style="{ height: `${inputHeight}rpx` }">
		<view class="send-msg" :style="{ bottom: `${keyboardHeight - 60}rpx` }">
			<view class="uni-textarea">
				<textarea
					@linechange="sendHeight"
					v-model="chatMsg"
					maxlength="300"
					confirm-type="send"
					placeholder="快来聊天吧~"
					:show-confirm-bar="false"
					:adjust-position="false"
					auto-height
				></textarea>
			</view>
			<button class="send-btn" @click="msg.sendMsg" :disabled="bol">{{ bol ? '发送中' : '发送' }}</button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			chatMsg: '',
			bol: false,
			//键盘高度
			keyboardHeight: 0,
			//底部消息发送高度
			bottomHeight: 0
		};
	},
	created() {
		uni.onKeyboardHeightChange((res) => {
			this.keyboardHeight = this.rpxTopx(res.height);
			if (this.keyboardHeight < 0) this.keyboardHeight = 0;
		});
	},
	computed: {
		windowHeight() {
			return this.rpxTopx(uni.getSystemInfoSync().windowHeight);
		},
		// 键盘弹起来的高度+发送框高度
		inputHeight() {
			return this.bottomHeight + this.keyboardHeight;
		}
	},
	methods: {
		sendHeight() {
			setTimeout(() => {
				let query = uni.createSelectorQuery();
				query.select('.send-msg').boundingClientRect();
				query.exec((res) => {
					this.bottomHeight = this.rpxTopx(res[0].height);
				});
			}, 10);
		},
		rpxTopx(px) {
			let deviceWidth = uni.getSystemInfoSync().windowWidth;
			let rpx = (750 / deviceWidth) * Number(px);
			return Math.floor(rpx);
		},
		toast(title) {
			uni.showToast({
				title,
				icon: 'none'
			});
		},
		inputStatus(bol) {
			if (bol) {
				uni.$emit('sendMsg', this.chatMsg);
				this.chatMsg = '';
			}
			this.bol = bol;
		},
		receiveMsg(msg) {
			uni.$emit('receiveMsg', msg);
		}
	}
};
</script>
<script lang="renderjs" module="msg">
	var msg
export default{
data(){
	return {
		callback:null
	}

},
	methods:{
		inputMsg(n,o,callback){
			console.log('我的输入',n);
			msg = n
			this.callback = callback
		},
		 extractData(input) {
		    let jsonObj;
		    // 判断输入是否为有效的JSON字符串
		    if (typeof input === "string") {
		        try {
		            jsonObj = JSON.parse(input);
		        } catch (e) {
		            // 输入不是有效的JSON字符串，使用正则表达式提取数据
		            const statusMatch = input.match(/"status":\s*(\d+)/);
		            const contentMatch = input.match(/"content":\s*"([^"]+)"/);
		            if (statusMatch && contentMatch) {
		                return { status: parseInt(statusMatch[1]), content: contentMatch[1] };
		            } else {
		                return { error: "Required fields are missing or invalid JSON structure" };
		            }
		        }
		    } else {
		        return { error: "Input is not a string" };
		    }
		    // 检查必要的字段是否存在并提取数据
		    if (jsonObj.result && jsonObj.result.header && jsonObj.result.payload) {
		        const status = jsonObj.result.header.status;
		        const content = jsonObj.result.payload.choices.text[0]?.content;

		        if (typeof status !== "undefined" && typeof content !== "undefined") {
		            return { status, content };
		        } else {
		            return { error: "Required fields are missing" };
		        }
		    } else {
		        return { error: "Invalid JSON structure" };
		    }
		},
		async sendMsg(n,o,ownerInstance){
			if(!msg){
			this.callback.callMethod('toast','请输入内容')
			return
			}
			this.callback.callMethod('inputStatus',true)
			const body = JSON.stringify({ inputVal: msg });
			 const myHeaders = new Headers();
			  myHeaders.append("Content-Type", "application/json");
		 const requestOptions = {
		    method: 'POST',
		    body,
			   headers: myHeaders,
		    redirect: 'follow'
		  };
		  try{
		  	 const res = await fetch("http://118.178.120.23:3000/send-message", requestOptions);
			  if (!res.body) {
				this.callback.callMethod('inputStatus',false)
			       return;
			  }
			  const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
			      while (true) {
			        const {done,value}= await reader.read();
					if(value){
						const answer = this.extractData(value);
						const {status,content} =answer
						const res =content
							this.callback.callMethod('receiveMsg',res)
						if(status == 2){
							this.callback.callMethod('inputStatus',false)
							break
						}
						if (done) {
							this.callback.callMethod('inputStatus',false)
							break
						}
					}

			      }
		  }catch(e){
			  this.callback.callMethod('inputStatus',false)
		  }
		}
	}
}
</script>
<style lang="scss">
/* 底部聊天发送栏 */
.chat-bottom {
	width: 100%;
	height: 100rpx;
	background: #f4f5f7;
	transition: all 0.1s ease;

	.send-msg {
		display: flex;
		align-items: flex-end;
		padding: 16rpx 30rpx;
		width: 100%;
		min-height: 177rpx;
		position: fixed;
		bottom: 0;
		background: #fff;
		transition: all 0.1s ease;
	}

	.uni-textarea {
		padding-bottom: 70rpx;
		textarea {
			width: 537rpx;
			min-height: 75rpx;
			max-height: 500rpx;
			background: #f1f1f1;
			border-radius: 40rpx;
			font-size: 32rpx;
			font-family: PingFang SC;
			color: #333333;
			line-height: 74rpx;
			padding: 5rpx 8rpx;
			text-indent: 30rpx;
		}
	}

	.send-btn {
		margin-bottom: 76rpx;
		margin-left: 25rpx;
		width: 120rpx;
		height: 75rpx;
	}
}
</style>
